<?php
/*
  +----------------------------------------------------------------------+
  | UCModComment.php                                                          |
  +----------------------------------------------------------------------+
  | Copyright (c) 2010 snda.com - Web Development Center                 |
  +----------------------------------------------------------------------+
  | Memcache engine                                                      |
  +----------------------------------------------------------------------+
  | Authors: Terry <leo9127@163.com>                                     |
  +----------------------------------------------------------------------+
*/
class UCModComment{
	protected $sender;
	protected $receiver;
	protected $writer;
	protected $channel_id;
	protected $cid;
	protected $write_sender = true;
	protected $write_receiver = true;
	
	function __construct(){
		require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');
		require_once(dirname(__FILE__).'/../../libraries/UCLibMISApi.php');
		require_once(dirname(__FILE__).'/../../config/comment/UCConfComment.php');
		require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
		require_once(dirname(__FILE__).'/../message/UCModMessageMgr.php');
		require_once(dirname(__FILE__).'/../../libraries/UCLibNewTip.php');
	}
	
	//传入变量处理
	protected function escape($data, $data_is_array = false) {
		if ($data_is_array) {
			$tmp = array();
			foreach ($data as $k => $v) {
				$tmp[$k] = htmlspecialchars(html_entity_decode($v,ENT_QUOTES),ENT_QUOTES);
			}
			return $tmp;
		}
		return htmlspecialchars(html_entity_decode($data,ENT_QUOTES),ENT_QUOTES);
  }
  
  protected function subStrCh($str,$len,$add=true){
  	$str_length=strlen($str);
		for($i=0;$i<$len;$i++){
			$temp_str=substr($str,0,1);
			if(ord($temp_str) > 127){
				$i++;
				if($i<$len){
					$new_str[]=substr($str,0,3);
					$str=substr($str,3);
				}
			}else{
				$new_str[]=substr($str,0,1);
				$str=substr($str,1);
			}
		}
		$new_str = join($new_str);
		if($add == true && $str_length > $len){
			$new_str = $new_str.'...';
		}
		return $new_str;
  }
  
  //频道号处理
  protected function setChannel($channel){
  	$channel = strtolower($this->escape($channel));
  	switch ($channel){
  		case "home":
  		$this->channel_id = 1000; //主页评论ID号
			break;
  		case "twitter":
  		$this->channel_id = 1001; //心情记录ID号
			break;
			case "app":
			$this->channel_id = 1002; //小应用ID号
			break;
			case "all":
			default:
			$this->channel_id = 0;
			break;
		}
  	return;
  }
  
  //将频道ID转为频道号
  public function channelSet($channel_id){
  	$channel_id = strtolower(trim($channel_id));
  	switch ($channel_id){
  		case 1000:
  		$channel = 'home';
			break;
			case 1001:
  		$channel = 'twitter';
			break;
			case 1002:
  		$channel = 'app';
			break;
			default:
			$channel = 'all';
			break;
		}
		return $channel;
	}
  
  //将传入的评论者和被评论者做赋值给变量
  protected function setUsername($sender,$writer='',$receiver=''){
  	$this->sender = strtolower($this->escape($sender));
  	$this->receiver = strtolower($this->escape($receiver));
  	$this->writer = strtolower($this->escape($writer));
  	return;
  }
  
  //生成MD5的散列KEY
  protected function getNewCid($sender,$writer='',$receiver=''){
		$this->sender = strtolower($this->escape($sender));
  	$this->receiver = strtolower($this->escape($receiver));
  	$this->writer = strtolower($this->escape($writer));
		list($usec, $sec) = explode(" ", microtime());
		$time = ((float)$usec + (float)$sec);
		$rand = rand(0,9500);
		return  md5($sender.$receiver.$writer.$time.$rand);
	}
	
	//获取发布者的IP地址
  protected function getClientIp(){
  	if (isset($_SERVER)) {
  		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  			return $_SERVER['HTTP_X_FORWARDED_FOR'];
  		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  			return $_SERVER['HTTP_CLIENT_IP'];
  		} else {
  			return $_SERVER['REMOTE_ADDR'];
  		}
  	} else {
  		if (getenv("HTTP_X_FORWARDED_FOR")) {
  			return getenv( "HTTP_X_FORWARDED_FOR");
  		} elseif (getenv("HTTP_CLIENT_IP")) {
  			return getenv("HTTP_CLIENT_IP");
  		} else {
  			return getenv("REMOTE_ADDR");
			}
		}
		return false;
	}
	
	//生成KEY
	protected function _getMemcacheKey($user, $custom_key = "receiver", $channel_id = 0, $module_id = 0, $sign=0){
		$user	= strtolower(trim($user));
		$custom_key	  = strtolower(trim($custom_key));
		$channel_id		= intval($channel_id);
		$module_id		= intval($module_id);
		$sign         = strtolower(trim($sign));
		return md5("comment_".$user."_".$custom_key."_c".$channel_id."_m".$module_id."_".$sign);
	}
	
	//查询用户是否对某条信息提交过评论
  protected function _submitComment($user,$channel_id = 0, $module_id = 0){
  	$channel_id = intval($channel_id);
  	$key = $this->_getMemcacheKey($user,"sender",$channel_id,$module_id,'repetition'); //判断用户是否参与过评论的标识
  	$cache = new UCLibCache('comment');
  	$ret = $cache->read($key);
  	if($ret === false && $ret != 'no'){
  		$pdo = UCLibPDOFactory::getPDO('sender',$this->sender,'commentdbconfig','commentdbconfig');
  		$pdo->query_one_with_prepare("SELECT cid FROM $pdo->database.$pdo->table WHERE module_id=? and channel_id=? and sender=?",array($data['module_id'],$this->channel_id,$this->sender));
  		//$sql = "SELECT cid FROM table_comment_sender WHERE module_id='".$data['module_id']."' and channel_id='".$this->channel_id."' and sender='".$this->sender."'";
  		//CMDB::dsn('sender', $this->sender);
  		//$row = CMDB::getRow($sql);
   		//CMDB::close();
  		if(!empty($cid)){
  			$cache->write($key,true);
  			return false;
  		}
  		$cache->write($key,'no');
  		return true;
  	}elseif($ret === 'no'){
  		return false;
  	}else{
  		return true;
  	}
  }
  
  //依据传入的参数更新相关CACHE
  protected function _renewCache($user,$channel_id=0,$module_id=0,$type='receiver',$spread=0){
   	$key = $this->_getMemcacheKey($user,$type,$channel_id,$module_id,$spread);
  	$cache = new UCLibCache('comment');
  	$cache->delete($key);
  	$cache->close();
  }
  
  //依据用户名和CID读取一条评论信息
  public function getCommentByCid($user,$cid,$type='sender'){
  	$user		= strtolower($this->escape($user));
		$cid    = $this->escape($cid);
		$type		= strtolower($this->escape($type));
		if($type != 'receiver' && $type != 'sender'){
			return false;
		}
		$key = $this->_getMemcacheKey($user, $type, 0, 0, $cid);
		$cache = new UCLibCache('comment');
		$row = $cache->read($key);
		if($row === false && $row != 'error'){
			if($type == 'receiver'){
				$table_name = "table_comment_receiver";
			}else{
				$table_name = "table_comment_sender";
			}
			$pdo = UCLibPDOFactory::getPDO($type,$user,'commentdbconfig');
			$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE ".$type."=? AND cid=? LIMIT 1";
			$ret = $pdo->query_one_row_with_prepare($sql,array($user,$cid));
			//$sql = "SELECT * FROM ".$table_name." WHERE ".$type."='".$user."' AND cid='".$cid."' LIMIT 1";
			//CMDB::dsn($type,$user);
			//$ret = CMDB::getRow($sql);
			//CMDB::close();
			if($ret === false || count($ret) == 0){
				$cache->write($key,'error',1800);
				$cache->close();
				return false;
			}
			$row = $ret;
			$cache->write($key,$row);
		}
		$cache->close();
		if($row == 'error'){
			$row = '';
		}
		return $row;
	}
	
	//记录用户有几条新评论新回复数据写入CACHE
	public function writeNewComment($user,$type){
		if(empty($user) || ($type != 'comment' && $type != 'reply')){
			return false;
		}
		if($type == 'comment'){
			$spread = 'developmentcomment';
		}else{
			$spread = 'developmentreply';
		}
		$key = $this->_getMemcacheKey($user, "reminder", $type, 0, $spread);
		$cache = new UCLibCache('comment');
		$row = $cache->read($key);
		if(empty($row)){
			$row = 1;
		}else{
			$row = intval($row)+1;
		}
		$cache->write($key,$row);
	}
	
	//将新评论置为0
	public function delNewComment($user){
		if(empty($user)){
			return false;
		}
		$key = array($this->_getMemcacheKey($user, "reminder", 'comment', 0, 'developmentcomment'),$this->_getMemcacheKey($user, "reminder", 'reply', 0, 'developmentreply'));
		$cache = new UCLibCache('comment');
		$cache->delete($key);
	}
	
	//获取用户现在新的评论以及回复
	public function getNewComment($user){
		$comkey = $this->_getMemcacheKey($user, "reminder", 'comment', 0, 'developmentcomment');
		$repkey = $this->_getMemcacheKey($user, "reminder", 'reply', 0, 'developmentreply');
		$cache = new UCLibCache('comment');
		$newcom = $cache->read($comkey);
		if(empty($newcom)){
			$newcom = 0;
		}
		$newrep = $cache->read($repkey);
		if(empty($newrep)){
			$newrep = 0;
		}
		return array('newcom'=>$newcom,'newrep'=>$newrep);
	}  
	
	//将评论信息写入DB
	public function insertComment($data,$persistent = 0){
		//$data = $this->escape($data, true);
		if (!$data['sender'] || !$data['content']){
  		trigger_error("Wrong Input!\n");
			return false;
  	}
  	if(!$data['receiver'] && $data['channel_id'] != 'app'){
  		trigger_error("Wrong Input!\n");
			return false;
		}
		if(!empty($data['cid']) && !empty($data['receiver'])){
			$row = $this->getCommentByCid($data['receiver'],$data['cid'],'sender');
			$data['writer'] = strtolower($this->escape($row['writer']));
			$data['comuser'] = $row['sender'];
			$data['parent_cid'] = $data['cid'];
		}else{
			$data['writer'] = $data['receiver'];
		}
		if(!empty($data['cid'])){
			if(empty($row)){
				$row = $this->getCommentByCid($data['receiver'],$data['cid'],'sender');
			}
			$data['channel_id'] = $row['channel_id'];
			$this->channel_id = $row['channel_id'];
			$data['module_id'] = $row['module_id'];
			if(empty($data['title'])){
				$data['title'] = $this->subStrCh($row['content'],40);
			}
			if(empty($data['custom_1'])){
				$data['custom_1'] = $row['custom_1'];
			}
			if(empty($data['custom_2'])){
				$data['custom_2'] = $row['custom_2'];
			}
			if(empty($data['custom_3'])){
				$data['custom_3'] = $row['custom_3'];
			}
			if(empty($data['custom_4'])){
				$data['custom_4'] = $row['custom_4'];
			}
		}
		$this->setUsername($data['sender'],$data['writer'],$data['receiver']);
		if(empty($this->channel_id)){
			$this->setChannel($data['channel_id']);
		}
  	$this->cid = $this->getNewCid($data['sender'],$data['writer'],$data['receiver']);
  	$data['cid'] = $this->cid;
  	$data['module_id'] = htmlspecialchars(html_entity_decode($data['module_id']));
  	if(empty($data['parent_cid'])){
  		$data['channel_id'] = $this->channel_id;
  	}
	if(!empty($data['parent_cid'])){
		$data['parent_cid'] = htmlspecialchars(html_entity_decode($data['parent_cid']));
	}
  	$data['writer'] = $this->writer;
  	$data['sender'] = $this->sender;
  	$data['receiver'] = $this->receiver;
  	if(empty($data['title'])){
			$data['title'] = $this->subStrCh($row['content'],40);
		}
		$data['title'] = addslashes($data['title']);
  	$data['content'] = addslashes(str_replace('\回复@我叫'.$data['receiver'].':\i','',$data['content']));
  	$data['adddate']	= time();
  	$data['ip'] = $this->getClientIp();
  	if(!empty($data['come_from'])){
  	  $data['come_from'] = $data['come_from'];
  	}else{
  	  $data['come_from'] = 'web';
  	}
	if(!empty($data['custom_1'])){
		$data['custom_1']	= intval($data['custom_1']);
	}
	if(!empty($data['custom_2'])){
		$data['custom_2']	= intval($data['custom_2']);
	}
	if(!empty($data['custom_3'])){
		$data['custom_3']	= $data['custom_3'];
	}
	if(!empty($data['custom_4'])){
		$data['custom_4']	= $data['custom_4'];
	}
	//信息审核
	$ret = UCLibMISApi::check($data['sender'], UC_MIS_CHANNEL_COMMENT, $data['content'], $data['cid']);
	if($ret == UC_MIS_RESULT_BAD){
		return 'mis_error';
	}
	if($ret == UC_MIS_RESULT_FREQ_LIMIT){
		return 'mis_limit';
	}
	//判断是否应许重复评论
  	if(!empty($persistent)){
   		if(!$this->_submitComment($this->sender,$this->channel_id,$data['module_id'])){
  			return false;
  		}
  	}
  	//往对象表中提交数据
  	$pdo = UCLibPDOFactory::getPDO('module',$this->channel_id.$data['module_id'],'commentdbconfig');
  	if(!$pdo->insert($data)){
  	//CMDB::dsn('module', $this->channel_id.$data['module_id']);
  	//if(!CMDB::insert('table_comment_module',$data)){
   		//CMDB::close();
  		return false;
  	}else{
  	  //CMDB::close();
  	  $this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','modulenewslist');
  	  $this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','moduleamount');
  		$this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','modulelisthomeasc');
  		$this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','modulelisthomedesc');
  		$this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','modulelistlastasc');
  		$this->_renewCache($this->channel_id.$data['module_id'],$this->channel_id,$data['module_id'],'module','modulelistlastdesc');
  	}
  		
  	//往用户评论发送表中插入数据
  	$pdo = UCLibPDOFactory::getPDO('sender',$this->sender,'commentdbconfig');
  	if(!$pdo->insert($data)){
  	//CMDB::dsn('sender', $this->sender);
  	//if(!CMDB::insert('table_comment_sender',$data)){
  		//CMDB::close();
  		return false;
  	}else{
  		$this->_renewCache($this->sender,0,0,'sender','senderlistHome');
  		$this->_renewCache($this->sender,0,0,'sender','senderlistLast');
  		$this->_renewCache($this->sender,0,0,'sender','senderamount');
  		$this->_renewCache($this->sender,$this->channel_id,0,'sender','senderlistHome');
  		$this->_renewCache($this->sender,$this->channel_id,0,'sender','senderlistLast');
  		$this->_renewCache($this->sender,$this->channel_id,0,'sender','senderamount');
  		//CMDB::close();
  	}
  	
  	//往用户评论接收表中插入数据
  	if(!empty($this->receiver)){
  		$data['new_msg_flag'] = 1;
  		$pdo = UCLibPDOFactory::getPDO('receiver',$this->receiver,'commentdbconfig');
  		if(!$pdo->insert($data)){
  		//CMDB::dsn('receiver', $this->receiver);
  		//if(!CMDB::insert('table_comment_receiver',$data)){
  			//CMDB::close();
  			return false;
  		}else{
  			$this->_renewCache($this->receiver,0,0,'receiver','receiverlistHome');
  			$this->_renewCache($this->receiver,0,0,'receiver','receiverlistLast');
  			$this->_renewCache($this->receiver,0,0,'receiver','receiveramount');
  			$this->_renewCache($this->receiver,$this->channel_id,0,'receiver','receiverlistHome');
  			$this->_renewCache($this->receiver,$this->channel_id,0,'receiver','receiverlistLast');
  			$this->_renewCache($this->receiver,$this->channel_id,0,'receiver','receiveramount');
  			if($this->channel_id == 1001){
  				$o = new UCLibNewTip($this->receiver);
  				$o->add(UCLibNewTip::MEMCACHE_KEY_REPLY);
  				if(!empty($data['parent_cid'])){
  					$this->writeNewComment($this->receiver,'reply');
  				}else{
  					$this->writeNewComment($this->receiver,'comment');
  				}
  			}
  			
  			//发送通知
  			if($this->channel_id == 1000){
  				$o = new UCLibNewTip($this->receiver);
  				$o->add(UCLibNewTip::MEMCACHE_KEY_COMMENT);
  				$o_mgr = new UCModMessageMgr($data['sender']);
  				if(!empty($data['parent_cid'])){
  					if($data['sender'] != $data['receiver']){
  						$o_mgr->sendNotice('new_leavemsg_reply',$data['receiver'],array('msg_sender_id'=>$data['sender'], 'source_user_id'=>$data['writer']));
  					}
  				}else{
   					if($data['sender'] != $data['receiver']){
  						$o_mgr->sendNotice('new_leave_msg', $data['receiver'], array('msg_sender_id'=>$data['sender']));
  					}
  				}
  			}
  			//CMDB::close();
  		}
  	}
  	
  	//往上一级的用户接收表中查入数据
  	if($this->receiver != $this->writer && !empty($this->writer)){
  		$data['receiver'] = $this->writer;
  		$data['new_msg_flag'] = 1;
  		$pdo = UCLibPDOFactory::getPDO('receiver',$this->writer,'commentdbconfig');
  		if(!$pdo->insert($data)){
   		//CMDB::dsn('receiver', $this->writer);
  		//if(!$ret = CMDB::insert('table_comment_receiver',$data)){
   			//CMDB::close();
  			return false;
  		}else{
  			$this->_renewCache($this->writer,0,0,'receiver','receiverlistHome');
  			$this->_renewCache($this->writer,0,0,'receiver','receiverlistLast');
  			$this->_renewCache($this->writer,0,0,'receiver','receiveramount');
  			$this->_renewCache($this->writer,$this->channel_id,0,'receiver','receiverlistHome');
  			$this->_renewCache($this->writer,$this->channel_id,0,'receiver','receiverlistLast');
  			$this->_renewCache($this->writer,$this->channel_id,0,'receiver','receiveramount');
  			if($this->channel_id == 1001){
  				$o = new UCLibNewTip($this->writer);
  				$o->add(UCLibNewTip::MEMCACHE_KEY_REPLY);
  				$this->writeNewComment($this->writer,'comment');
  			}
  			if($this->channel_id == 1000){
  				$o = new UCLibNewTip($this->writer);
  				$o->add(UCLibNewTip::MEMCACHE_KEY_COMMENT);
  				$o_mgr = new UCModMessageMgr($data['sender']);
  				if($data['writer'] != $data['sender']){
  					$o_mgr->sendNotice('new_leave_msg', $data['writer'], array('msg_sender_id'=>$data['sender']));
  				}
  			}
  			//CMDB::close();
  		}
  	}
  	return $this->cid;
  }
  
  //删除评论
  public function deleteComment($cid, $user, $type='sender'){
  	$user		= strtolower($this->escape($user));
		$cid    = $this->escape($cid);
		$type		= strtolower($this->escape($type));
		if($type != 'sender' && $type != 'receiver'){
			return false;
		}
		//读取该条评论信息
		$row = $this->getCommentByCid($user,$cid,$type);
		if($type == 'sender' && $row['sender'] != $user){
			return false;
		}
		if($type == 'receiver' && $row['receiver'] != $user){

			return false;
		}
		if($row == false){
			return false;
		}
		//判断用户是否可以删除全部数据
		if($user == $row['writer']){
			//删除在我的内容下面的评论
			$pdo = UCLibPDOFactory::getPDO('module',$row['channel_id'].$row['module_id'],'commentdbconfig');
  		if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer']))){
			//$sql = "UPDATE table_comment_module SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."'";
			//CMDB::dsn('module', $row['channel_id'].$row['module_id']);
			//if(!CMDB::query($sql)){
				//CMDB::close();
  			return false;
  		}else{
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelisthomeasc');
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelisthomedesc');
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelistlastasc');
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelistlastdesc');
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulenewslist');
  			$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','moduleamount');
  			//CMDB::close();
  		}
  		
  		//删除我接收到的评论信息
  		$pdo = UCLibPDOFactory::getPDO('receiver',$row['receiver'],'commentdbconfig');
  		if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'receiver'=>$row['receiver']))){
 			//$sql = "UPDATE table_comment_receiver SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."' and receiver='".$row['receiver']."'";
  		//CMDB::dsn('receiver', $row['receiver']);
  		//if(!CMDB::query($sql)){
				//CMDB::close();
  			return false;
  		}else{
  			$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistHome');
  			$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistLast');
  			$this->_renewCache($row['receiver'],0,0,'receiver','receiveramount');
  			$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistHome');
  			$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistLast');
  			$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiveramount');
  			//CMDB::close();
  		}
  		
  		//删除用户收到的评论信息
  		if(!empty($row['comuser']) && $row['writer'] != $row['comuser']){
  			$pdo = UCLibPDOFactory::getPDO('receiver',$row['comuser'],'commentdbconfig');
  			if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'receiver'=>$row['comuser']))){
  			//$sql = "UPDATE table_comment_receiver SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."' and receiver='".$row['comuser']."'";
  			//CMDB::dsn('receiver', $row['comuser']);
  			//if(!CMDB::query($sql)){
					//CMDB::close();
  				return false;
  			}else{
  				$this->_renewCache($row['comuser'],0,0,'receiver','receiverlistHome');
  				$this->_renewCache($row['comuser'],0,0,'receiver','receiverlistLast');
  				$this->_renewCache($row['comuser'],0,0,'receiver','receiveramount');
  				$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiverlistHome');
  				$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiverlistLast');
  				$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiveramount');
  				//CMDB::close();
  			}
  		}
  		
			//删除发送者的信息
			$pdo = UCLibPDOFactory::getPDO('sender',$row['sender'],'commentdbconfig');
  		if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'sender'=>$row['sender']))){
			//$sql = "UPDATE table_comment_sender SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."' and sender='".$row['sender']."'";
			//CMDB::dsn('sender', $row['sender']);
			//if(!CMDB::query($sql)){
				//CMDB::close();
  			return false;
  		}else{
   			$this->_renewCache($row['sender'],0,0,'sender','senderlistHome');
  			$this->_renewCache($row['sender'],0,0,'sender','senderlistLast');
  			$this->_renewCache($row['sender'],0,0,'sender','senderamount');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistHome');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistLast');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderamount');
  			//CMDB::close();
  		}
  	}else{
  		if($user == $row['receiver']){
  			$pdo = UCLibPDOFactory::getPDO('receiver',$row['receiver'],'commentdbconfig');
  			if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'receiver'=>$row['receiver']))){
  			//$sql = "UPDATE table_comment_receiver SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."' and receiver='".$row['receiver']."'";
  			//CMDB::dsn('receiver', $row['receiver']);
  			//if(!CMDB::query($sql)){
					//CMDB::close();
  				return false;
  			}else{
  				$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistHome');
  				$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistLast');
  				$this->_renewCache($row['receiver'],0,0,'receiver','receiveramount');
  				$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistHome');
  				$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistLast');
  				$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiveramount');
  				//CMDB::close();
  			}
  		}else if($user == $row['sender']){
  			$pdo = UCLibPDOFactory::getPDO('sender',$row['sender'],'commentdbconfig');
  			if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'sender'=>$row['sender']))){
  			//$sql = "UPDATE table_comment_sender SET del=1 WHERE cid='".$cid."' and writer='".$row['writer']."' and sender='".$row['sender']."'";
				//CMDB::dsn('sender', $row['sender']);
				//if(!CMDB::query($sql)){
					//CMDB::close();
  				return false;
  			}else{
  				$this->_renewCache($row['sender'],0,0,'sender','senderlistHome');
  				$this->_renewCache($row['sender'],0,0,'sender','senderlistLast');
  				$this->_renewCache($row['sender'],0,0,'sender','senderamount');
  				$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistHome');
  				$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistLast');
  				$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderamount');
  				//CMDB::close();
  			}
  	 	}else{
  	 		return false;
  		}
  	}
  	//删除单条评论的CACHE
  	$key = $this->_getMemcacheKey($user, $type, 0, 0, $cid);
		$cache = new UCLibCache('comment');
		$cache->delete($key);
		$cache->close();
  	return true;
  }
  
  //MIS依据发送人删除评论
  public function deleteCommentMis($cid, $user, $type='sender'){
  	$user		= strtolower($this->escape($user));
		$cid    = $this->escape($cid);
		$type		= strtolower($this->escape($type));
		if($type != 'sender' && $type != 'receiver'){
			return false;
		}
		//读取该条评论信息
		$row = $this->getCommentByCid($user,$cid,$type);
		if($row == false){
			return false;
		}
		//删除内容下面的评论
		$pdo = UCLibPDOFactory::getPDO('module',$row['channel_id'].$row['module_id'],'commentdbconfig');
  	if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer']))){
  		return false;
  	}else{
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelisthomeasc');
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelisthomedesc');
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelistlastasc');
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulelistlastdesc');
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','modulenewslist');
  		$this->_renewCache($row['channel_id'].$row['module_id'],$row['channel_id'],$row['module_id'],'module','moduleamount');
  	}
  	//删除接收者的评论信息
  	$pdo = UCLibPDOFactory::getPDO('receiver',$row['receiver'],'commentdbconfig');
  	if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'receiver'=>$row['receiver']))){
  		return false;
  	}else{
  		$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistHome');
  		$this->_renewCache($row['receiver'],0,0,'receiver','receiverlistLast');
  		$this->_renewCache($row['receiver'],0,0,'receiver','receiveramount');
  		$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistHome');
  		$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiverlistLast');
  		$this->_renewCache($row['receiver'],$row['channel_id'],0,'receiver','receiveramount');
  	}
  	//删除主贴用户收到的评论信息
  	if(!empty($row['comuser']) && $row['writer'] != $row['comuser']){
  		$pdo = UCLibPDOFactory::getPDO('receiver',$row['comuser'],'commentdbconfig');
  		if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'receiver'=>$row['comuser']))){
  			return false;
  		}else{
  			$this->_renewCache($row['comuser'],0,0,'receiver','receiverlistHome');
  			$this->_renewCache($row['comuser'],0,0,'receiver','receiverlistLast');
  			$this->_renewCache($row['comuser'],0,0,'receiver','receiveramount');
  			$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiverlistHome');
  			$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiverlistLast');
  			$this->_renewCache($row['comuser'],$row['channel_id'],0,'receiver','receiveramount');
  			}
  		}
  		//删除发送者的信息
			$pdo = UCLibPDOFactory::getPDO('sender',$row['sender'],'commentdbconfig');
  		if(!$pdo->update(array('del'=>1),array('cid'=>$cid,'writer'=>$row['writer'],'sender'=>$row['sender']))){
  			return false;
  		}else{
   			$this->_renewCache($row['sender'],0,0,'sender','senderlistHome');
  			$this->_renewCache($row['sender'],0,0,'sender','senderlistLast');
  			$this->_renewCache($row['sender'],0,0,'sender','senderamount');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistHome');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderlistLast');
  			$this->_renewCache($row['sender'],$row['channel_id'],0,'sender','senderamount');
  		}
  		//删除单条评论的CACHE
  	$key = $this->_getMemcacheKey($user, $type, 0, 0, $cid);
		$cache = new UCLibCache('comment');
		$cache->delete($key);
		$cache->close();
  	return true;
  }
  
  //读取评论条数
  public function amountComment($channel_id, $module_id=0, $type='module',$user=''){
  	$module_id = strtolower($this->escape($module_id));
		$type      = strtolower($this->escape($type));
		$user		   = strtolower($this->escape($user));
		if($type != 'module' &&  $type != 'receiver' && $type != 'sender'){
			return false;
		}
		if($type != 'module' && empty($user)){
			return false;
		}
		if($type == 'module' && empty($module_id)){
			return false;
		}
		$this->setChannel($channel_id);
  	if($type == 'module'){
  		$key = $this->_getMemcacheKey($this->channel_id.$module_id, $type, $this->channel_id, $module_id, 'moduleamount');
  		$cache = new UCLibCache('comment');
  		$row = $cache->read($key);
  		if($row === false && $row != 'error'){
  			$pdo = UCLibPDOFactory::getPDO('module',$this->channel_id.$module_id,'commentdbconfig');
  			$sql = "SELECT count(*) as tatal FROM $pdo->database.$pdo->table WHERE channel_id=? and module_id=? and del=?";
  			$params = array($this->channel_id,$module_id,0);
  			$ret = $pdo->query_one_row_with_prepare($sql,$params);
  			//CMDB::dsn('module',$this->channel_id.$module_id);
  			//$ret = CMDB::getRow($sql);
   			//CMDB::close();
  			if(!$ret){
  				$cache->write($key,'error',1800);
  				$cache->close();
  				return '0';
  			}
  			$row = $ret['tatal'];
  			$cache->write($key,$row);
  		}
  		if($row == 'error'){
  			$row = 0;
  		}
  		return $row;
  	}else if($type == 'receiver'){
  		$key = $this->_getMemcacheKey($user, $type, $this->channel_id, $module_id, 'receiveramount');
  		$cache = new UCLibCache('comment');
  		$row = $cache->read($key);
  		if($row === false && $row != 'error'){
  			$params = array();
  			$WHERE = " WHERE receiver=? and del=?";
  			$params[] = $user;
  			$params[] = 0;
  			if(!empty($this->channel_id)){
  				$WHERE .= " and channel_id=?";
  				$params[] = $this->channel_id;
  			}
  			if(!empty($module_id)){
  				$WHERE .= " and module_id=?";
  				$params[] = $module_id;
  			}
  			$pdo = UCLibPDOFactory::getPDO('receiver',$user,'commentdbconfig');
  			$sql = "SELECT count(*) as tatal FROM $pdo->database.$pdo->table".$WHERE;
  			$ret = $pdo->query_one_row_with_prepare($sql,$params);
  			//CMDB::dsn('receiver',$user);
  			//$ret = CMDB::getRow($sql);
  			//CMDB::close();
  			if(!$ret){
  				$cache->write($key,'error',1800);
  				$cache->close();
  				return '0';
  			}
  			$row = $ret['tatal'];
  			$cache->write($key,$row);
  		}
  		if($row == 'error'){
  			return '0';
  		}else{
  			return $row;
  		}
  	}else if($type == 'sender'){
  		$key = $this->_getMemcacheKey($user, $type, $this->channel_id, $module_id, 'senderamount');
  		$cache = new UCLibCache('comment');
  		$row = $cache->read($key);
  		if($row === false && $row != 'error'){
  			$params = array();
  			$WHERE = " WHERE sender=? and del=?";
  			$params[] = $user;
  			$params[] = 0;
  			if(!empty($this->channel_id)){
  				$WHERE .= " and channel_id=?";
  				$params[] = $this->channel_id;
  			}
  			if(!empty($module_id)){
  				$WHERE .= " and module_id=?";
  				$params[] = $module_id;
  			}
  			$pdo = UCLibPDOFactory::getPDO('sender',$user,'commentdbconfig');
  			$sql = "SELECT count(*) as tatal FROM $pdo->database.$pdo->table".$WHERE;
  			$ret = $pdo->query_one_row_with_prepare($sql,$params);
  			//CMDB::dsn('sender',$user);
  			//$ret = CMDB::getRow($sql);
  			//CMDB::close();
  			if(!$ret){
  				$cache->write($key,'error',1800);
  				$cache->close();
  				return '0';
  			}
  			$row = $ret['tatal'];
  			$cache->write($key,$row);
  		}
  		if($row == 'error'){
  			return '0';
  		}else{
  			return $row;
  		}
  	}else{
  		return '0';
  	}
  }
  
  //批量读取评论条数
  public function amountCommentMulti($channel_id,$modulearray,$type='module',$user=''){
  	$channel_id = strtolower($this->escape($channel_id));
		$type      = strtolower($this->escape($type));
		$user		   = strtolower($this->escape($user));
		if($type != 'module' &&  $type != 'receiver' && $type != 'sender'){
			return false;
		}
		if(empty($channel_id) || !is_array($modulearray)){
			return false;
		}
		$this->setChannel($channel_id);
		$cacheKey = array();
		if($type == 'module'){
			foreach($modulearray as $key=>$val){
				$cacheKey[] = $this->_getMemcacheKey($this->channel_id.$val, $type, $this->channel_id, $val, 'moduleamount');
			}
		}else if($type == 'receiver'){
			foreach($modulearray as $key=>$val){
				$cacheKey[] = $this->_getMemcacheKey($user, $type, $this->channel_id, $val, 'receiveramount');
			}
		}else if($type == 'sender'){
			foreach($modulearray as $key=>$val){
				$cacheKey[] = $this->_getMemcacheKey($user, $type, $this->channel_id, $val, 'senderamount');
			}
		}
		//读取数据
		$channel = 'comment';
		$cache = new UCLibCache($channel);
		$rows = $cache->read_multi($cacheKey);
		$cache->close();
		$newsrows = array();
		foreach($modulearray as $key=>$val){
			if($type == 'module'){
				$cacheKeyinfo = $this->_getMemcacheKey($this->channel_id.$val, $type, $this->channel_id, $val, 'moduleamount');
			}else if($type == 'receiver'){
				$cacheKeyinfo = $this->_getMemcacheKey($user, $type, $this->channel_id, $val, 'receiveramount');
			}else if($type == 'sender'){
				$cacheKeyinfo = $this->_getMemcacheKey($user, $type, $this->channel_id, $val, 'senderamount');
			}
			if(!isset($rows[$channel.'_'.$cacheKeyinfo])){
				$newsrows[$val] = $this->amountComment($channel_id,$val);
			}else{
				if($rows[$channel.'_'.$cacheKeyinfo] == 'error'){
					$newsrows[$val] = 0;
				}else{
					$newsrows[$val] = $rows[$channel.'_'.$cacheKeyinfo];
				}
			}
		}
		return $newsrows;
	}
  
  //读取页面上展示的评论数 默认返回最新的10条
  public function getCommentByTopic($channel_id, $module_id,$page_size = 10){
  	if(empty($channel_id) || empty($module_id)){
  		return false;
  	}
  	$module_id = strtolower($this->escape($module_id));
		$page_size = intval($page_size);
		$this->setChannel($channel_id);
		$total = $this->amountComment($channel_id, $module_id, 'module');
		if($total == 0){
			return array('total'=>0,'comlist'=>array());
		}
		//读取CACHE数据
		$key = $this->_getMemcacheKey($this->channel_id.$module_id,'module',$this->channel_id, $module_id, 'modulenewslist');
		$cache = new UCLibCache('comment');
  	$row = $cache->read($key);
  	//$row = false;
  	if($row === false && $row != 'error'){
  		$pdo = UCLibPDOFactory::getPDO('module',$this->channel_id.$module_id,'commentdbconfig');
  		$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE channel_id=? and module_id=? and del=? ORDER BY adddate DESC LIMIT ?,?";
  		$params = array($this->channel_id,$module_id,0,0,$page_size);
  		$ret = $pdo -> query_with_prepare($sql,$params);
   		//CMDB::dsn('module',$this->channel_id.$module_id);
  		//$ret = CMDB::getRows($sql);
  		//CMDB::close();
  		if($ret === false || !is_array($ret)){
  			$cache->write($key,'error',1800);
  			$cache->close();
  			return false;
  		}
  		$ret = array_reverse($ret);
  		$row = $ret;
  		$cache->write($key,$row);
  		$cache->close();
  	}
  	if($this->channel_id == 1000 && !empty($row) && is_array($row)){
  		$row = array_reverse($row);
  	}
  	if($row == 'error'){
  		return false;
  	}else{
  		return array('total'=>$total,'comlist'=>$row);
  	}
  }
  
  //读取页面展示上的评论数 默认每页20条，第一页和最后一页CACHE
  public function getCommentByList($channel_id, $module_id, $page=0, $sort='asc' ,$page_size = 20){
    $sort = strtolower($this->escape($sort));
  	if(!$channel_id || !$module_id){
  		return false;
  	}
   	if($sort != 'asc' && $sort != 'desc'){
  	  return false;
  	}
   	$module_id = strtolower($this->escape($module_id));
  	$page      = intval($page);
		$page_size = intval($page_size);
		$this->setChannel($channel_id);
		$total = $this->amountComment($channel_id, $module_id, 'module');
		if($total == 0){
			return array('page'=>array('size'=>$page_size,'current'=>$page,'total_rows'=>0,'total_pages'=>0),'rows'=>array());
		}
		$pagecount = ceil($total/$page_size);
		if($page > $pagecount){
			$page = $pagecount;
		}
		if($page == 0){
			$page = 1;
		}
		$row = false;
		if($page == 1){
			$key = $this->_getMemcacheKey($this->channel_id.$module_id,'module',$this->channel_id, $module_id, 'modulelisthome'.$sort);
		}elseif($page == $pagecount){
			$key = $this->_getMemcacheKey($this->channel_id.$module_id,'module',$this->channel_id, $module_id, 'modulelistlast'.$sort);
		}else{
			$key = false;
		}
		if(!empty($key)){
			$cache = new UCLibCache('comment');
			$row = $cache->read($key);
			$cache->close();
		}
		//$row = false;
		if($row === false && $row != 'error'){
		  if($sort == 'asc'){
		    $SORT = 'ASC';
		  }else{
		    $SORT = 'DESC';
		  }
		  $pageinfo=array('size'=>$page_size,'current'=>$page,'total_rows'=>$total,'total_pages'=>$pagecount);
		  $pdo = UCLibPDOFactory::getPDO('module',$this->channel_id.$module_id,'commentdbconfig');
			$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE channel_id=? and module_id=? and del=? ORDER BY adddate ".$SORT." LIMIT ?,?";
			$params = array($this->channel_id,$module_id,0,(($page-1)*$page_size),$page_size);
			$list  = $pdo->query_with_prepare($sql,$params);
			//CMDB::dsn('module',$this->channel_id.$module_id);
			//$ret = CMDB::getPage($sql, $page, $total, $page_size);
			//CMDB::close();
			if(!$list || !is_array($list)){
				if(!$key){
					$cache = new UCLibCache('comment');
					$cache->write($key,'error',1800);
  				$cache->close();
  				return false;
  			}else{
  				return false;
  			}
  		}
  		$row['page'] = $pageinfo;
  		$row['rows'] = $list;
  		if(!empty($key)){
  			$cache = new UCLibCache('comment');
  			$cache->write($key,$row);
  			$cache->close();
  		}
  	}
  	if($this->channel_id == 1000){
			$o = new UCLibNewTip($row['rows'][0]['writer']);
			$o->clear(UCLibNewTip::MEMCACHE_KEY_COMMENT);
		}
  	return $row;
  }
  	
  	
  
  //读取用户评论列表，每页默认显示20条第一页和最后一页CACHE
  public function getCommentUserList($user,$type='receiver',$channel_id='all', $module_id=0,$page=0, $page_size = 20){
  	if(!$user){
  		return false;
  	}
  	if($type != 'receiver' && $type != 'sender'){
  		return false;
  	}
  	if($type == 'receiver'){
  		$home = 'receiverlistHome';
  		$last = 'receiverlistLast';
  		$table_name = 'table_comment_receiver';
  	}else{
  		$home = 'senderlistHome';
  		$last = 'senderlistLast';
  		$table_name = 'table_comment_sender';
  	}
  	$user = strtolower($this->escape($user));
  	$type = strtolower($this->escape($type));
  	$module_id = strtolower($this->escape($module_id));
  	$page      = intval($page);
		$page_size = intval($page_size);
		$this->setChannel($channel_id);
		if($this->channel_id == 1001 && $type == 'receiver'){
			$o = new UCLibNewTip($user);
			$o->clear(UCLibNewTip::MEMCACHE_KEY_REPLY);
		}
		$total = $this->amountComment($channel_id, $module_id, $type,$user);
		if($total == 0){
			return array('page'=>array('size'=>$page_size,'current'=>$page,'total_rows'=>0,'total_pages'=>0),'rows'=>array());
		}
		$row = false;
		if($page == 1){
			$key = $this->_getMemcacheKey($user,$type,0, $module_id, $home);
		}elseif($page == $pagecount){
			$key = $this->_getMemcacheKey($user,$type,0, $module_id, $last);
			$this->delNewComment($user);
		}else{
			$key = false;
		}
		if(!empty($key)){
			$cache = new UCLibCache('comment');
			$row = $cache->read($key);
			$cache->close();
		}
		//$row = false;
		if($row === false && $row != 'error'){
			$params = array();
			$WHERE = " WHERE ".$type."=? and del=?";
			$params[] = $user;
			$params[] = 0;
			if(!empty($this->channel_id)){
				$WHERE .= " and channel_id=?";
				$params[] = $this->channel_id;
			}
			if(!empty($module_id)){
				$WHERE .= " and module_id=?";
				$params[] = $module_id;
			}
			$pageinfo=array('size'=>$page_size,'current'=>$page,'total_rows'=>$total,'total_pages'=>$pagecount);
			$pdo = UCLibPDOFactory::getPDO($type,$user,'commentdbconfig');
			$sql = "SELECT * FROM $pdo->database.$pdo->table".$WHERE." ORDER BY adddate DESC LIMIT ?,?";
			$params[] = (($page-1)*$page_size);
			$params[] = $page_size;
			$ret  = $pdo->query_with_prepare($sql,$params);
			//CMDB::dsn($type,$user);
			//$ret = CMDB::getPage($sql, $page, $total, $page_size);
			//CMDB::close();
			if(!$ret || !is_array($ret)){
				if(empty($key)){
					$cache = new UCLibCache('comment');
					$cache->write($key,'error',1800);
  				$cache->close();
  				return false;
  			}else{
  				return false;
  			}
  		}
  		$row['rows'] = $ret;
  		$row['page'] = $pageinfo;
  		if(!empty($key)){
  			$cache = new UCLibCache('comment');
  			$cache->write($key,$row);
  			$cache->close();
  		}
  	}
  	return $row;
  }
}
?>